import {login, logout, getInfo} from '@/api/login'
import Cookies from "js-cookie";
import {getToken, removeToken, setToken} from '@/utils/auth'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      isRewritePsd: false
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            const {token, godDefect,  userId, userName} = res.data;
            setToken(token);
            this.permissions = [godDefect];
            console.log(this.permissions)
            this.token = res.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.data;
            this.isRewritePsd = res.data.resetLogin;
            this.roles = ['ROLE_DEFAULT']
            this.permissions = [user.godDefect]
            this.id = user.userId
            this.name = user.userName
            resolve(this.isRewritePsd)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
        })
      }
    }
  })

export default useUserStore
